package com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.biz.service.impl;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.paic.mhis.common.base.intergration.dao.CommonDAO;
import com.paic.mhis.core.auth.biz.service.UserDetails;
import com.paic.mhis.hcpms.evaluation.common.biz.service.EvaluationWorkFlowService;
import com.paic.mhis.hcpms.evaluation.common.constants.EvaluationConstants;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.biz.service.EvaluationIllegalService;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.constants.EvaluationOrgConstants;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dao.EvaluationOrgDao;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.EvalMarkDeatilInfoDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.EvalMarkInfoDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.EvalMarkUserComfirmDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.EvaluationMarkContentDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.EvaluationPointCutInfo;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.evaluationIntegrity.dto.IntegrityEvalDTO;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.orgReview.constants.OrgReviewConstants;
import com.paic.mhis.hcpms.evaluation.evaluationOrg.orgReview.dao.OrgApproveDao;

/**
 * 
 * @author EX-LUORONG001
 * 
 */
@Component("evaluationIllegalServiceImpl")
public class EvaluationIllegalServiceImpl implements EvaluationIllegalService {
	@Autowired
	private EvaluationOrgDao evaluationOrgDao;
	@Autowired
	private CommonDAO commonDAO;
	@Autowired
	private EvaluationWorkFlowService workFlowService;

	@Autowired
	private OrgApproveDao approveDao;

	public Map<String, Object> getIntgrityEvalInfo(IntegrityEvalDTO bean) {
		Map<String, Object> map1 = new HashMap<String, Object>();
		// 一、根据诚信考评id及考评类别：机构，药店；获取诚信考评信息
		map1.put("intgrityEvalInfo", evaluationOrgDao.loadAuditiCaseDTOByCode(bean));
		return map1;
	}

	public Map<String, Object> getIntgrityEvalTypeInfo(IntegrityEvalDTO bean) {
		Map<String, Object> map = new HashMap<String, Object>();
		// 二、根据诚信考评id及考评类别：机构，药店；获取诚信考评各分组类详细信息
		List<EvalMarkUserComfirmDTO> cUserComfirmList = evaluationOrgDao.getEvalMarkUserComfirmInfo(bean
				.getEvaluationCode());
		for (EvalMarkUserComfirmDTO e : cUserComfirmList) {
			if (e.getEvaluationSumScroe() != null && e.getEvaluationScroe() != null) {
				double sum = Double.parseDouble(e.getEvaluationSumScroe());
				double eva = Double.parseDouble(e.getEvaluationScroe());
				if (eva == 0) { // 当考评得分为0 时，初始化考评得分
					e.setEvaluationScroe((new Double(sum)).toString());
					evaluationOrgDao.updateInitScroe(e.getIntgrityEvalChildId(), e.getEvaluationCode(),
							e.getEvaluationScroe());
				}
			}
		}
		map.put("intgrityEvalTypeInfo", cUserComfirmList);
		return map;
	}

	public Map<String, Object> getIntgrityEvalDetail(String ruleId, String evalChildId, String targetType) {
		Map<String, Object> map = new HashMap<String, Object>();

		List<EvaluationMarkContentDTO> contentList = this.evaluationOrgDao.queryEvaluationContentDTO(ruleId);

		this.getContentList(contentList, evalChildId, targetType);// 参数：考核内容列表，诚信考评表子表主建，扣分对象类型(01医疗机构)
		map.put("data", contentList);// 设置考核内容列表
		return map;
	}

	public void getContentList(List<EvaluationMarkContentDTO> contentList, String evalChildId, String targetType) {
		if (contentList != null && contentList.size() > 0) {

			for (EvaluationMarkContentDTO contentBean : contentList) {

				String contentId = contentBean.getId();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("evalChildId", evalChildId);// 诚信考评表子表主建
				map.put("evaluationInfoId", contentId);// 考核内容id
				map.put("targetType", targetType);// 扣分类型
				// 根据诚信考评表子表主建id查找诚信考评表主表机构编号:this.evaluationOrgDao.findOrgCodeByEvalChildId(evalChildId);
				String orgCode=this.evaluationOrgDao.findOrgCodeByEvalChildId(evalChildId);
				map.put("orgCode", orgCode);// 机构编号
				List<EvalMarkDeatilInfoDTO> markRuleList = this.evaluationOrgDao.queryEvaluationMarkRuleDTO(map);

				contentBean.setList(markRuleList); // 设置考核内容下面的扣分细则列表
				this.getMarkRuleList(markRuleList, evalChildId,orgCode,targetType);
			}
		}
	}

	public void getMarkRuleList(List<EvalMarkDeatilInfoDTO> markRuleList, String evalChildId,String orgCode,String targetType) {
		if (markRuleList != null && markRuleList.size() > 0) {
			for (EvalMarkDeatilInfoDTO markRuleBean : markRuleList) {
				
				markRuleBean.setEvalChildId(evalChildId);
				markRuleBean.setOrgCode(orgCode);
				markRuleBean.setTargetType(targetType);

				BigDecimal upperValue = markRuleBean.getUpperValue();// 获取上限分值
				BigDecimal lowerValue = markRuleBean.getLowerValue();// 获取下限分值
				if (upperValue != null && lowerValue != null) {
					markRuleBean.setMarkContent(markRuleBean.getMarkContent() + " " + lowerValue + "-" + upperValue
							+ "分");// 扣分细则：由'评分标准名称'和'上,下限分值'组成
				} else if (upperValue != null) {
					markRuleBean.setMarkContent(markRuleBean.getMarkContent() + " " + upperValue + "分");
				} else if (lowerValue != null) {
					markRuleBean.setMarkContent(markRuleBean.getMarkContent() + " " + lowerValue + "分");
				}
				String markRuleId = markRuleBean.getId();
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("evalChildId", evalChildId);
				map.put("markRuleId", markRuleId);
				List<EvalMarkInfoDTO> markValueList = this.evaluationOrgDao.queryEvaluationMarkValueDTO(map);

				markRuleBean.setList(markValueList); // 设置扣分细则下面的扣分值列表
			}
		}
	}

	@Transactional
	public Map<String, Object> saveIntgrityEvalInfo(EvalMarkUserComfirmDTO bean, UserDetails user) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		bean.setStatus(bean.getOnlySave());
		bean.setCreatedBy(user.getUsername());
		bean.setUpdatedBy(user.getUsername());
		String businessId = this.saveUpdateIntgrityEvalChild(bean);// 添加诚信考评子表信息

		List<EvalMarkDeatilInfoDTO> eList = bean.getEvalMarkDeatilInfoList();// 确认人信息

		this.saveUpdateEvalMarkInfo(eList, businessId, user.getUsername());
		// 获取当前考评分值
		String score = evaluationOrgDao.getCountScore(businessId);
		bean.setEvaluationScroe(score);
		evaluationOrgDao.updateIntgrityEvalChild(bean);
		// onlySave：1，暂存；0，保存
		if (StringUtils.hasText(bean.getOnlySave()) && "0".equals(bean.getOnlySave())) {
			// 1.根据考评id获取所有的考评子表中是否存在暂存信息，不存在则走流程
			int count = evaluationOrgDao.getCountEvaluation(bean.getEvaluationCode());
			if (count <= 0) {
				String status = EvaluationConstants.STATUSTHREE;
				evaluationOrgDao.updateIntgrityEvalStatus(status, user.getUsername(), bean.getEvaluationCode());
				// 流程
				workFlowService.startWorkFlow(bean.getEvaluationCode(), user, EvaluationConstants.MODULE_TYPE_05);
				map.put("flag", EvaluationOrgConstants.FLAG_TURE);
			}
		}
		map.put(EvaluationOrgConstants.STATE_KEY, EvaluationOrgConstants.FLAG_TURE);
		map.put(EvaluationOrgConstants.MSG_KEY, EvaluationOrgConstants.OPERATE_SUCCESS);
		return map;
	}

	/**
	 * 判断诚信考评子表是否存在当前数据，存在修改；不存在则添加
	 * 
	 * @param eComfirmDTO
	 */
	public String saveUpdateIntgrityEvalChild(EvalMarkUserComfirmDTO eComfirmDTO) {

		EvalMarkUserComfirmDTO parameter = new EvalMarkUserComfirmDTO();
		parameter.setEvaluationCode(eComfirmDTO.getEvaluationCode());
		parameter.setEvaluRuleId(eComfirmDTO.getEvaluRuleId());

		String buinessId = evaluationOrgDao.queryIntgrityEvalChild(parameter);
		if (StringUtils.hasText(buinessId)) {
			evaluationOrgDao.updateIntgrityEvalChild(eComfirmDTO);
		} else {
			buinessId = commonDAO.getUUID();
			eComfirmDTO.setId(buinessId);
			eComfirmDTO.setIsValid(EvaluationOrgConstants.IS_VALID);
			evaluationOrgDao.addIntgrityEvalChild(eComfirmDTO);
		}
		return buinessId;
	}

	/**
	 * 判断扣分确认人及确认是否存在当前数据，存在修改；不存在则添加
	 * 
	 * @param eComfirmDTO
	 */
	public void saveUpdateEvalMarkInfo(List<EvalMarkDeatilInfoDTO> eDeatilList, String businessId, String userName) {
		if (null != eDeatilList && eDeatilList.size() > 0) {
			for (EvalMarkDeatilInfoDTO evalDto : eDeatilList) {
				evalDto.setEvalChildId(businessId);
				evalDto.setIsValid(EvaluationOrgConstants.IS_VALID);
				evalDto.setCreatedBy(userName);
				evalDto.setUpdatedBy(userName);
				evaluationOrgDao.addUpdateEvalMarkUser(evalDto);

				List<EvalMarkInfoDTO> eDList = evalDto.getList();// 确认信息
				if (null != eDList && eDList.size() > 0) {
					for (EvalMarkInfoDTO eInfoDTO : eDList) {
						eInfoDTO.setEvalChildId(businessId);
						eInfoDTO.setIsValid(EvaluationOrgConstants.IS_VALID);
						eInfoDTO.setCreatedBy(userName);
						eInfoDTO.setUpdatedBy(userName);
						evaluationOrgDao.addUpdateEvalIntegriyUser(eInfoDTO);
					}
				}
			}
		}
	}

	/**
	 * 保存诚信考评 确认的信息,修改诚信考评表的考评总分
	 */
	@Transactional
	@Override
	public Map<String, Object> saveEvaluationInfoConfirm(EvalMarkUserComfirmDTO bean, UserDetails user)
			throws Exception {

		bean.setUpdatedBy(user.getUsername());
		bean.setCreatedBy(user.getUsername());
		String onlySave = bean.getOnlySave();

		Map<String, Object> map = new HashMap<String, Object>();

		EvalMarkUserComfirmDTO parameter = new EvalMarkUserComfirmDTO();
		parameter.setEvaluationCode(bean.getEvaluationCode());
		parameter.setEvaluRuleId(bean.getEvaluRuleId());

		String evalChildId = evaluationOrgDao.queryIntgrityEvalChild(parameter);

		if (StringUtils.hasText(evalChildId)) {
			bean.setIntgrityEvalChildId(evalChildId);

			this.processEvalIntegirtyMarkInfo(bean, user);
			this.processEvalMarkUserInfo(bean, user);

			String score = evaluationOrgDao.getCountScore(evalChildId);
			String getScore = "";
			if (StringUtils.hasText(score)) {
				// 考评得分=考评总分-扣的分
				getScore = String.valueOf(Double.parseDouble(bean.getEvaluationSumScroe()) - Double.parseDouble(score));
				bean.setEvaluationScroe(getScore);
			} else {
				bean.setEvaluationScroe(bean.getEvaluationSumScroe());
			}
			if (StringUtils.hasText(onlySave) && onlySave.equals("1")) { // 暂存
				bean.setStatus("1"); // 暂存
			} else if (StringUtils.hasText(onlySave) && onlySave.equals("0")) {// 保存
				bean.setStatus("0"); // 保存
			}
			evaluationOrgDao.updateIntgrityEvalChild(bean);
			// ----------------------------------------------------
			// evaluationOrgDao.findByChildId(evalChildId);// 获取考评编码
			evaluationOrgDao.updateEvaluationSumScroe(evaluationOrgDao.findByChildId(evalChildId), getScore);// 根据考评编码修改诚信考评表的考评总分
			// ----------------------------------------------------
			// onlySave：1，暂存；0，保存
			if (StringUtils.hasText(bean.getOnlySave()) && "0".equals(bean.getOnlySave())) {
				// 1.根据考评id获取所有的考评子表中是否存在暂存信息，不存在则走流程
				long allCount = this.evaluationOrgDao.queryEvalChildRecord(bean.getEvaluationCode(), null);

				long saveCount = this.evaluationOrgDao.queryEvalChildRecord(bean.getEvaluationCode(), "0"); // 保存的状态
				if (allCount == saveCount) {
					// String status = EvaluationConstants.STATUSTHREE;
					IntegrityEvalDTO integrityEvalDTO = new IntegrityEvalDTO();
					integrityEvalDTO.setEvaluationCode(bean.getEvaluationCode());

					IntegrityEvalDTO dto = evaluationOrgDao.loadAuditiCaseDTOByCode(integrityEvalDTO);
					// 判断 如果当前流程没有走过流程则启动流程 反之则重新提交流程
					if (EvaluationConstants.STATUSONE.equals(dto.getStatus())) {
						// 开始流程
						workFlowService.startWorkFlow(bean.getEvaluationCode(), user,
								EvaluationConstants.MODULE_TYPE_05);
					} else {
						// 重新提交流程
						Map<String, String> condition = new HashMap<String, String>();
						condition.put(EvaluationConstants.EVALUATION_INTEGRITY_TYPE,
								EvaluationConstants.EVALUATION_INTEGRITY_TYPE_01);
						workFlowService.processWorkFlow(bean.getEvaluationCode(), user, condition,
								EvaluationConstants.MODULE_TYPE_05);
					}
					evaluationOrgDao.updateIntgrityEvalStatus(EvaluationConstants.STATUSTHREE, user.getUsername(),
							bean.getEvaluationCode());
					// 如果是审核撤回，要重置之前全部审核信息

					evaluationOrgDao.resetIntgrityReviewInfo(bean.getEvaluationCode(), EvaluationConstants.STATUSTHREE,
							user.getUsername());

					map.put("flag", "true");
					map.put("msg", "操作成功");
				}
			}

			map.put("success", "true");
			map.put("msg", "操作成功");

		} else {
			map.put("success", "false");
			map.put("msg", "操作失败");
		}

		return map;
	}

	/**
	 * 处理诚信考评扣分确认人信息表的数据
	 * 
	 * @param bean
	 * @param user
	 */
	@Transactional
	private void processEvalMarkUserInfo(EvalMarkUserComfirmDTO bean, UserDetails user) {

		String evalChildId = bean.getIntgrityEvalChildId(); // 诚信考评子表的主键
		// 先保存诚信考评扣分确认表的信息
		List<EvalMarkDeatilInfoDTO> evalMarkDeatilInfoList = bean.getEvalMarkDeatilInfoList();
		if (evalMarkDeatilInfoList != null && evalMarkDeatilInfoList.size() > 0) {
			for (EvalMarkDeatilInfoDTO detailBean : evalMarkDeatilInfoList) {

				String evaluationUser = detailBean.getEvaluationUser();
				String markDetailValueId = detailBean.getMarkDetailValueId(); // 扣分细则表ID

				this.evaluationOrgDao.deleteIntegrityMarkUserInfoByChildId(evalChildId, markDetailValueId);
				if (StringUtils.hasText(evaluationUser)) {
					detailBean.setUpdatedBy(user.getUsername());
					detailBean.setCreatedBy(user.getUsername());
					detailBean.setIsValid(OrgReviewConstants.is_valid_0);
					detailBean.setEvalChildId(evalChildId);
					this.evaluationOrgDao.addEvalMarkUser(detailBean);
				}

			}
		}

	}

	/**
	 * 先处理诚信考评扣分确认表的信息
	 * 
	 * @param bean
	 * @param user
	 */
	@Transactional
	private void processEvalIntegirtyMarkInfo(EvalMarkUserComfirmDTO bean, UserDetails user) {

		String evalChildId = bean.getIntgrityEvalChildId(); // 诚信考评子表的主键
		// 先保存诚信考评扣分确认表的信息
		List<EvalMarkDeatilInfoDTO> evalMarkDeatilInfoList = bean.getEvalMarkDeatilInfoList();
		if (evalMarkDeatilInfoList != null && evalMarkDeatilInfoList.size() > 0) {
			for (EvalMarkDeatilInfoDTO detailBean : evalMarkDeatilInfoList) {

				List<EvalMarkInfoDTO> evalMarkInfoList = detailBean.getList();
				if (evalMarkInfoList != null && evalMarkInfoList.size() > 0) {

					for (EvalMarkInfoDTO currentBean : evalMarkInfoList) {

						String markValueId = currentBean.getMarkValueId(); // 扣分值表ID
						String isConfirm = currentBean.getIsConfirm(); // 是否确定

						// 删除后在保存
						this.evaluationOrgDao.deleteIntegrityMarkByChildId(evalChildId, markValueId);

						if (StringUtils.hasText(isConfirm) && isConfirm.equals("0")) { // 1代表保存
							currentBean.setIsValid(OrgReviewConstants.is_valid_0);
							currentBean.setCreatedBy(user.getUsername());
							currentBean.setUpdatedBy(user.getUsername());
							currentBean.setEvalChildId(evalChildId);
							this.evaluationOrgDao.addEvalIntegriyUser(currentBean);
						}

					}
				}

			}
		}
	}


	@Override
	public List<EvaluationPointCutInfo> queryPointValue(String orgCode,
			String standardScoreId, String targetType) {
		
		
		List<EvaluationPointCutInfo> list=this.evaluationOrgDao.queryPointValue(orgCode, standardScoreId, targetType);
		
		if(list!=null && list.size()>0){
			for(EvaluationPointCutInfo bean :list){
				String caseType=bean.getCaseType();
				String caseNo=bean.getCaseNo();
				
				if(caseType.equals("01")){ //预警
					EvaluationPointCutInfo currentBean=this.evaluationOrgDao.queryEvaluationPointCutInfoWarInfo(caseNo);
					if(null!=currentBean){
						bean.setAuditUser(currentBean.getAuditUser());
						bean.setProcessUser(currentBean.getProcessUser());
						bean.setCaseTime(currentBean.getCaseTime());
						bean.setBusinessCode(currentBean.getBusinessCode());
						bean.setCaseTypeDesc("预警");
					}
				}
				
				
			    if(caseType.equals("02")){ //稽核
			    	EvaluationPointCutInfo currentBean=this.evaluationOrgDao.queryEvaluationPointCutInfoAuditCaseInfo(caseNo);
			    	if(null!=currentBean){
	           	        bean.setAuditUser(currentBean.getAuditUser());
						bean.setProcessUser(currentBean.getProcessUser());
						bean.setCaseTime(currentBean.getCaseTime());
						bean.setBusinessCode(currentBean.getBusinessCode());
						bean.setCaseTypeDesc("稽核");
			    	}
			    	
				}
				
           
				
				
			}
		}
		
		
		    return list;
	}

}
